<template>
	<view class="container">
		<view class="visitor">
			<view class="outside">
				<view class="within">
					<view class="info">
						<view class="name">
							<text>{{infoData.xm}}</text>
							<!-- <text class="classType">【门诊】</text> -->
						</view>
						<view class="cord">
							卡号
						</view>
						<view>{{$desensitizationNormalStr(infoData.kh)}}</view>
					</view>
				</view>
			</view>
		</view>
		<view class="screenType">
			<view class="typeLeft">
				<uni-datetime-picker type="date" :end="endTime" v-model="beginTime"
					@change="beginChange($event)">{{beginTime}}</uni-datetime-picker>
				<view style="margin: 0 10rpx;">-</view>
				<uni-datetime-picker type="date" :start="beginTime" v-model="endTime"
					@change="endChange($event)">{{endTime}}</uni-datetime-picker>
			</view>
			<view class="typeRight" style="display: flex;align-items: center;" v-if="payList.length > 0 && selectStatus == '1'">
				<text style="margin-right: 10rpx;">全选</text>
				<u-checkbox-group v-model="checkedAll" @change="checkboxGroupChange">
					<u-checkbox name="all"></u-checkbox>
				</u-checkbox-group>
			</view>
		</view>
		<view class="noCard" v-if="payList.length == 0">
			<view class="images">
				<img src="@/static/images/noCard.png" alt="">
				<view>
					未查询到信息
				</view>
			</view>
		</view>
		<view class="list" v-else>
			<scroll-view class="scroll-view_H" scroll-y="true" style="height: calc(100vh - 450rpx);">
				<view class="doctorItem" v-for="(a,parentIndex) in payList" :key="a.DoctorCode">
					<view class="top">
						<view class="dot"></view>
						<text
							style="font-size: 30rpx;color: #333;flex: 1;margin-left: 12rpx;font-weight: bold;">{{a.lists[0].DepartmentName}}</text>
						<text style="font-size: 28rpx;color: #999;">开单医生：</text>
						<text style="font-size: 28rpx;color: #333;">{{a.lists[0].DoctorName}}</text>
					</view>
					<view class="items" v-for="(item,index) in a.lists" :key="item.prescriptionNo">
						<view class="title">
							<view class="ischeck_ico"  @click="selectStatus == '1' ? chuFang(parentIndex,index) : ''">
								<img v-if="item.isChecked" src="@/static/images/pay_check_ico.png"
									style="width: 38rpx;height: 38rpx;" alt="">
								<img v-else src="@/static/images/pay_noCheck_ico.png"
									style="width: 38rpx;height: 38rpx;" alt="">
							</view>
							<text class="names">{{item.feeType}}</text>
							<view class="btn">
								{{item.bz==0?'待支付':'已支付'}}
							</view>
						</view>
						<view @click="goDtl(item)">
							<view class="icd">
								<text class="left">开单时间</text>
								<text>{{item.createDate != null && item.createDate != ''? item.createDate.substring(0,19):''}}</text>
							</view>
							<view class="time">
								<text class="left">需付款</text>
								<text class="moneyw"><text class="money">￥</text><text
										class="nums">{{item.orderFee}}</text></text>
							</view>
						</view>

					</view>

				</view>

			</scroll-view>
		</view>
		<view class="footer_btn" v-if="payList.length > 0">
			<view style="display: flex;align-items: center;flex: 1;padding-left: 30rpx;">
				<text>总计 ￥</text>
				<text style="font-size: 34rpx;color: #323232;">{{allAmount}}</text>
			</view>
			<u-button type="primary" text="立即支付" @click="comformPay"></u-button>
		</view>
		
	</view>
</template>
<script src="http://res.wx.qq.com/open/js/jweixin-1.2.0.js"></script>
<script>
	import {
		getPayMentListSmf,
		payUnifiedOrder,
		checkOutpatientPayment,
		checkYKT,
		createOrderZfb
	} from "@/api/pay/index.js"
	import {
		multiply,
		add,
		subtract,
		divide
	} from "accurate-core";
	import {
		encrypt,
		decrypt
	} from '@/utils/sm4Util.js'
   import { getConfigKey } from "@/api/home/home.js";
	export default {
		components: {},
		data() {
			return {
				infoData: {
					xm:'',
					kh:'',
				},
				beginTime: '',
				endTime: '',
				checkType: '0',
				payList: [],
				checkedAll: ['all'],
				allAmount: '0.00',
				selectStatus:'',
			}
		},
		onLoad(options) {
			let oneDay = 24 * 60 * 60 * 1000
			this.beginTime = this.$parseTime(new Date(Date.now() - 7 * oneDay), '{y}-{m}-{d}')
			this.endTime = this.$parseTime(new Date(), '{y}-{m}-{d}')
			
			this.infoData.kh = options.cardNum;
			this.getInfo();
			this.getConfig()
		},
		onPullDownRefresh() {
			this.getInfo()
		},
		methods: {
			/* 获取参数配置-是否支持缴费列表选择1:可选，qt:不可选 */
			getConfig() {
				getConfigKey('isPaySelective').then(res => {
					this.selectStatus = res.msg;
				});
			},
			// 检验卡号有效性并查询用户信息
			getInfo(){
				checkYKT({
					cardNum: this.infoData.kh
				}).then(res => {
					if (res.code == 200 && res.data) {
						this.infoData = res.data[0];
						this.getList();
					}
				});
			},
			getList() {
				let obj = {
					name: this.infoData.xm,
					cardNum: this.infoData.kh,
					beginTime: this.beginTime,
					endTime: this.endTime,
					bz: this.checkType,
				}
				getPayMentListSmf(obj).then(res => {
					//数据请求完成之后停止下拉刷新
					uni.stopPullDownRefresh();
					if (res.data.length > 0) {
						let doctorList = []
						res.data.map(item => {
							doctorList.push(item.DoctorCode)
						})
						doctorList = [...new Set(doctorList)]
						let resultList = []
						for (let i = 0; i < doctorList.length; i++) {
							let itemObj = {
								DoctorCode: doctorList[i],
								lists: []
							}
							for (let k = 0; k < res.data.length; k++) {
								if (res.data[k].DoctorCode == doctorList[i]) {
									res.data[k].isChecked = true
									itemObj.lists.push(res.data[k])
								}
							}
							resultList.push(itemObj)
						}
						this.checkedAll = ['all']
						this.payList = resultList
			
					} else {
						this.checkedAll = []
						this.payList = []
					}
					this.pjTotalPriceCount()
			
				})
			},
			/* 确认支付 */
			comformPay() {
				let prescriptionCod = []
				for (let i = 0; i < this.payList.length; i++) {
					for (let k = 0; k < this.payList[i].lists.length; k++) {
						if (this.payList[i].lists[k].isChecked) {
							prescriptionCod.push(this.payList[i].lists[k].prescriptionNo)
						}
					}
				}
				if (prescriptionCod.length == 0) {
					return this.$msg("请选择要支付的处方");
				}
				/* 处方校验 */
				checkOutpatientPayment({
					cfhList: prescriptionCod.join('*'),
					name: this.infoData.xm,
					cardNum: this.infoData.kh
				}).then(res => {
					if (res.code == 200) {
						this.payByMyself(prescriptionCod.join('*'), this.allAmount)
					}

				});
			},
			// 微信统一下单
			payByMyself(recipelNum, orderAmount){
				let _that = this
				let openid = uni.getStorageSync('openid') || ''
				let obj = {
					"hospitalCode": '', //医院微信唯一标识
					"openId": openid, //微信唯一标识
					"bh": this.infoData.kh, //住院号/卡号
					"recipelNum": recipelNum, //处方号（门诊业务专用字段
					"orderAmount": orderAmount, //订单金额
					"orderDesc": "门诊支付-" + this.infoData.xm, //订单描述（医卡通，预约，门诊支付 住院押金）
					"payType": "weChat", //支付类型（weChat:微信 Alipay:支付宝）
					"orderType": "3" //订单类型（1医卡通，2预约，3门诊支付 4住院押金）
				}
				let param = {
					params: encrypt(JSON.stringify(obj))
				}
				payUnifiedOrder(param).then(resporns => {
					WeixinJSBridge.invoke('getBrandWCPayRequest', {
							"appId": resporns.data.appId,
							"timeStamp": resporns.data.timeStamp,
							"nonceStr": resporns.data.nonceStr,
							"package": resporns.data.package,
							"signType": "MD5",
							"paySign": resporns.data.paySign,
						},
						function(resporns) { // 调起微信支付成功
							if (resporns.err_msg ==
								"get_brand_wcpay_request:ok") {
								_that.getList()
								_that.$msg("支付成功!");
							
							} else if (resporns.err_msg ==
								"get_brand_wcpay_request:cancel") {
								_that.$msg("用户取消支付!");
							} else {
								_that.$msg("支付失败,请重新支付!" + resporns.err_msg);
							}
						});
				})
			},
			/* 动态计算项目总价*/
			pjTotalPriceCount() {
				let newVal = this.payList;
				let datas = []
				for (let i = 0; i < newVal.length; i++) {
					for (let k = 0; k < newVal[i].lists.length; k++) {
						if (newVal[i].lists[k].isChecked) {
							datas.push(newVal[i].lists[k])
						}
					}
				}
				let gentle = 0
				for (let i = 0; i < datas.length; i++) {
					gentle = add(gentle, Number(datas[i].orderFee))
				}
				this.allAmount = this.jsAllAmount(Math.floor(gentle * 1000) / 1000)
			},
			jsAllAmount(num) {
				var num1 = parseFloat(num);
				if (!isNaN(num1)) {
					num1 = Math.round(num1 * 100) / 100;
					var str = num1.toString();
					var rs = str.indexOf('.');
					if (rs < 0) {
						rs = str.length;
						str += '.';
					}
					while (str.length <= rs + 2) {
						str += '0';
					}
					return str
				}
			},
			chuFang(parentIndex, index) {
				let isChecked = !this.payList[parentIndex].lists[index].isChecked
				this.payList[parentIndex].lists[index].isChecked = isChecked
				this.pjTotalPriceCount()
			},
			checkboxGroupChange(e) {
				for (let i = 0; i < this.payList.length; i++) {
					for (let k = 0; k < this.payList[i].lists.length; k++) {
						if (e.length > 0) {
							this.payList[i].lists[k].isChecked = true
						} else {
							this.payList[i].lists[k].isChecked = false
						}
					}
				}
				this.pjTotalPriceCount()
			},
			
			
			goDtl(item) {
				uni.navigateTo({
					url: '/pages/pay/details?prescriptionNo=' + item.prescriptionNo
				})
			},
			/* 开始日期 */
			beginChange(e) {
				this.getList()
			},
			/* 结束日期 */
			endChange(e) {
				this.getList()
			},
			
		}
	}
</script>

<style lang="scss" scoped>
	page {
		background-color: rgb(245, 245, 245);
	}

	.pay_type {
		width: 80vw;
		padding: 24rpx;

		.center {
			background-color: #F3F8FF;
			border-radius: 10rpx;
			margin: 60rpx 0;

			.item {
				display: flex;
				align-items: center;
				padding: 40rpx 30rpx;
			}

			.borderBottom {
				border-bottom: 1px solid #eee;
			}
		}

		.top {
			display: flex;
			align-items: center;
			justify-content: space-between;


		}
	}

	.footer_btn {
		position: fixed;
		bottom: 0;
		left: 0;
		display: flex;
		align-items: center;
		justify-content: space-around;
		text-align: center;
		width: 100%;
		padding: 24rpx;
		background-color: #fff;

		.u-button {
			width: 40%;
		}
	}

	.noCard {
		width: 100%;
		text-align: center;
		color: #666666;
		padding: 24rpx 0 0 0;
		margin-top: 72rpx;
		color: #808080;

		.images {
			width: 100%;
			margin-bottom: 40rpx;
			color: #666666;

			img {
				width: 55%;
				text-align: center;
			}
		}
	}

	.list {
		padding: 24rpx;
		margin: 0 auto;

		.doctorItem {
			background-color: #fff;
			border-radius: 8px;
			padding: 24rpx 0 24rpx 0;
			margin-bottom: 24rpx;

			.top {
				display: flex;
				align-items: center;
				padding: 0 24rpx 24rpx 24rpx;
				border-bottom: 1px solid #eee;

				.dot {
					width: 6rpx;
					height: 28rpx;
					border-radius: 5rpx;
					background-color: #4D8EFF;
				}
			}

			.items {
				background-color: #F3F8FF;
				border-radius: 8px;
				padding-bottom: 12rpx;
				margin: 24rpx 24rpx 0 24rpx;

				.title {
					padding: 24rpx;
					display: flex;
					font-size: 28rpx;
					font-weight: 600;
					align-items: center;
					border-bottom: 1rpx solid #eee;
					margin-bottom: 12rpx;
					display: flex;
					align-items: center;
					justify-content: space-between;

					.ischeck_ico {
						display: flex;
						align-items: center;
					}

					.names {
						flex: 1;
						overflow: hidden;
						white-space: nowrap;
						text-overflow: ellipsis;
						margin-left: 12rpx;
					}

					.btn {
						width: 100rpx;
						font-size: 28rpx;
						color: #FF6430;
						text-align: right;
					}
				}

				.name,
				.icd,
				.time,
				.dept {
					display: flex;
					justify-content: space-between;
					padding: 12rpx 24rpx;
					font-size: 28rpx;

					.left {
						color: #999;
						width: 130rpx;
					}

					.payBtn {
						border-radius: 20px;
						background-color: #4D8EFF;
						color: #fff;
						padding: 8rpx 24rpx;
						text-align: center;
					}

					.moneyw {
						display: flex;
						font-size: 24rpx;
						color: #999;

						.money {
							color: #000;
						}

						.nums {
							font-size: 40rpx;
							color: #000;
						}
					}
				}
			}
		}


	}

	.screenType {
		width: 100%;
		display: flex;
		align-items: center;
		padding: 20rpx;
		background-color: rgb(92, 147, 249);
		justify-content: space-around;
		color: #fff;

		.typeLeft,
		.typeRight {
			display: flex;
			align-items: center;
		}
	}

	.visitor {
		width: 100%;
		// background-color: rgb(92, 147, 249);
		background: url('@/static/images/report-small-bg.png') no-repeat left center, linear-gradient(180deg, rgba(197, 218, 255, 1) 0%, rgba(92, 147, 249, 1) 100%);
		background-size: auto 100%;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 24rpx 24rpx 0 24rpx;
		color: #3C537D;

		.outside {
			width: 100%;
			background-color: #fff;
			padding: 12rpx 12rpx 0 12rpx;
			border-radius: 8px 8px 0 0;
			background: url('@/static/images/card_bg.png') no-repeat;
			background-size: 100% 100%;

			.within {
				border-radius: 8px 8px 0 0;

				.info {
					padding: 16rpx 28rpx 20rpx;
					font-size: 34rpx;

					.name {
						display: flex;
						align-items: center;

						.classType {
							display: inline-block;
							margin: 0 36rpx;
						}

						.btn {
							font-size: 28rpx;
							padding: 7rpx 14rpx;
							background: linear-gradient(90deg, rgba(77, 142, 255, 1) 0%, rgba(94, 150, 247, 1) 100%);
							color: #fff;
							display: flex;
							align-items: center;
							border-radius: 5px;
						}
					}

					.cord {
						font-size: 28rpx;
						padding: 16rpx 0 8rpx;
					}
				}
			}
		}
	}
</style>